﻿using System;
using System.Web.Caching;
using DemoLib.Providers.Service;
using DemoLib.Providers.Shared.Contracts;
using OutputCache = DemoLib.Providers.Shared.Models.OutputCache;

namespace DemoLib.Providers.Web
{
    public class CustomOutputCacheProvider : OutputCacheProvider
    {
        private readonly IOutputCacheService _outputCacheService;

        public CustomOutputCacheProvider()
        {
            _outputCacheService = new OutputCacheService();
        }
        public override object Get(string key)
        {
            var cacheObject = _outputCacheService.Get(key);
            return cacheObject != null ? cacheObject.CacheObject : null;
        }

        public override object Add(string key, object entry, DateTime utcExpiry)
        {
            AddOrUpdate(key, entry, utcExpiry);
            return entry;
        }

        public override void Set(string key, object entry, DateTime utcExpiry)
        {
            AddOrUpdate(key, entry, utcExpiry);
        }

        public override void Remove(string key)
        {
            _outputCacheService.Remove(key);
        }

        private object AddOrUpdate(string key, object entry, DateTime utcExpiry)
        {
            return _outputCacheService.AddOrUpdate(new OutputCache
                {
                    Key = key,
                    CacheObject = entry,
                    Expiry = utcExpiry
                });
        }
    }
}
